<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="header">
      <view class="header-content">
        <text class="title">🎤 语音添加记录</text>
        <text class="subtitle">说出完整的喝奶信息，一键生成记录</text>
      </view>
    </view>

    <!-- 语音录制主区域 -->
    <view class="voice-main-section">
      <!-- 使用示例 -->
      <view class="example-section">
        <text class="example-title">💬 说话示例</text>
        <view class="example-list">
          <view class="example-item" v-for="(example, index) in examples" :key="index" @click="speakExample(example)">
            <text class="example-text">"{{ example }}"</text>
            <text class="example-icon">🔊</text>
          </view>
        </view>
      </view>

      <!-- 语音录制区域 -->
      <view class="voice-recorder-section">
        <voice-recorder 
          @apply-result="applyVoiceResult"
          @recognition-success="onVoiceSuccess"
          @recognition-error="onVoiceError"
        />
        <text class="voice-tip">💡 按住按钮录音，松开完成识别</text>
      </view>

      <!-- 当前表单数据预览 -->
      <view v-if="hasFormData" class="form-preview">
        <view class="preview-header">
          <text class="preview-title">📝 当前记录信息</text>
          <text class="preview-clear" @click="clearFormData">清空</text>
        </view>
        
        <view class="preview-content">
          <view class="preview-item" v-if="formData.feedingType">
            <text class="preview-label">喂养方式：</text>
            <text class="preview-value">{{ feedingTypeNames[formData.feedingType] }}</text>
          </view>
          
          <view class="preview-item" v-if="formData.amount">
            <text class="preview-label">奶量：</text>
            <text class="preview-value">{{ formData.amount }}ml</text>
          </view>
          
          <view class="preview-item" v-if="formData.time">
            <text class="preview-label">时间：</text>
            <text class="preview-value">{{ formatDisplayTime(formData.time) }}</text>
          </view>
          
          <view class="preview-item" v-if="formData.notes">
            <text class="preview-label">备注：</text>
            <text class="preview-value">{{ formData.notes }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-section">
          <button class="btn-secondary" @click="editRecord">手动编辑</button>
          <button class="btn-primary" @click="saveRecord">保存记录</button>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <view class="empty-icon">🎤</view>
        <text class="empty-title">开始语音记录</text>
        <text class="empty-desc">按住按钮录音，松开完成识别</text>
      </view>
    </view>

    <!-- 历史记录快览 -->
    <view class="recent-records">
      <view class="recent-header">
        <text class="recent-title">📊 今日记录</text>
        <text class="recent-count">{{ todayRecords.length }}条</text>
      </view>
      
      <view v-if="todayRecords.length > 0" class="recent-list">
        <view v-for="(record, index) in todayRecords.slice(0, 3)" :key="index" class="recent-item">
          <view class="recent-time">{{ record.time }}</view>
          <view class="recent-info">
            <text class="recent-amount">{{ record.amount }}ml</text>
            <text class="recent-type">{{ feedingTypeNames[record.feeding_type] }}</text>
          </view>
        </view>
        
        <view v-if="todayRecords.length > 3" class="view-more" @click="viewAllRecords">
          <text>查看全部 {{ todayRecords.length }} 条记录 ></text>
        </view>
      </view>
      
      <view v-else class="recent-empty">
        <text>今天还没有记录哦</text>
      </view>
    </view>

    <!-- 快速操作提示 -->
    <view class="quick-tips">
      <text class="tips-title">💡 语音使用技巧</text>
      <view class="tips-list">
        <text class="tip-item">🎤 按住语音按钮开始录音</text>
        <text class="tip-item">🔊 松开按钮完成录音并自动识别</text>
        <text class="tip-item">📝 完整表达："喂了120毫升母乳，下午2点"</text>
        <text class="tip-item">🎯 说话清晰，语速适中，安静环境下使用</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'VoiceRecord',
  data() {
    return {
      formData: {
        feedingType: null,
        amount: null,
        time: null,
        notes: null
      },
      
      // 喂养方式映射
      feedingTypeNames: {
        'direct': '亲喂',
        'bottle_breast': '喝母乳', 
        'bottle_formula': '喝奶粉'
      },
      
      // 示例语句
      examples: [
        "给宝宝喂了120毫升母乳，下午2点30分，宝宝吃得很香",
        "刚喂了150毫升奶粉，现在是上午10点",
        "宝宝亲喂了20分钟，晚上8点开始的"
      ],
      
      // 今日记录
      todayRecords: []
    }
  },
  
  computed: {
    hasFormData() {
      return this.formData.feedingType || this.formData.amount || this.formData.time || this.formData.notes
    }
  },
  
  onLoad() {
    this.loadTodayRecords()
  },
  
  onShow() {
    this.loadTodayRecords()
  },
  
  methods: {
    // 处理语音识别成功
    onVoiceSuccess(data) {
      console.log('语音识别成功:', data)
      uni.showToast({
        title: '语音识别成功',
        icon: 'success',
        duration: 1000
      })
    },

    // 处理语音识别错误
    onVoiceError(error) {
      console.error('语音识别失败:', error)
    },

    // 应用语音识别结果
    applyVoiceResult(parsedInfo) {
      try {
        // 更新表单数据
        if (parsedInfo.amount) {
          this.formData.amount = parsedInfo.amount
        }
        
        if (parsedInfo.feedingType) {
          this.formData.feedingType = parsedInfo.feedingType
        }
        
        if (parsedInfo.time) {
          this.formData.time = parsedInfo.time
        }
        
        if (parsedInfo.notes) {
          this.formData.notes = parsedInfo.notes
        }
        
        // 如果没有时间，设置为当前时间
        if (!this.formData.time) {
          const now = new Date()
          this.formData.time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
        }
        
        uni.showToast({
          title: '语音信息已识别',
          icon: 'success',
          duration: 2000
        })
        
        // 震动反馈
        uni.vibrateShort()
        
      } catch (error) {
        console.error('应用语音结果失败:', error)
        uni.showToast({
          title: '应用语音信息失败',
          icon: 'none'
        })
      }
    },
    
    // 示例语句点击（可以用于语音播放示例）
    speakExample(text) {
      uni.showToast({
        title: '可以按此格式说话',
        icon: 'none',
        duration: 2000
      })
    },
    
    // 格式化显示时间
    formatDisplayTime(timeStr) {
      if (!timeStr) return ''
      
      const today = new Date()
      const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`
      
      return `${todayStr} ${timeStr}`
    },
    
    // 清空表单数据
    clearFormData() {
      this.formData = {
        feedingType: null,
        amount: null,
        time: null,
        notes: null
      }
      
      uni.showToast({
        title: '已清空',
        icon: 'success',
        duration: 1000
      })
    },
    
    // 手动编辑记录
    editRecord() {
      // 跳转到标准的喝奶记录页面，并传递当前数据
      const params = encodeURIComponent(JSON.stringify(this.formData))
      uni.navigateTo({
        url: `/pages/feeding-record/feeding-record?data=${params}`
      })
    },
    
    // 保存记录
    async saveRecord() {
      try {
        // 验证必填信息
        if (!this.formData.amount || this.formData.amount < 10) {
          uni.showToast({
            title: '请确保奶量不少于10ml',
            icon: 'none'
          })
          return
        }
        
        if (!this.formData.feedingType) {
          uni.showToast({
            title: '请确保已识别喂养方式',
            icon: 'none'
          })
          return
        }
        
        uni.showLoading({
          title: '保存中...'
        })
        
        // 准备保存数据
        const now = new Date()
        const date = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
        
        // 调用云函数保存记录
        const result = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'add',
            data: {
              date: date,
              amount: this.formData.amount,
              time: this.formData.time,
              notes: this.formData.notes || '',
              feeding_type: this.formData.feedingType,
              source: 'voice_page'
            }
          }
        })
        
        uni.hideLoading()
        
        if (result.result.success) {
          uni.showToast({
            title: '记录保存成功',
            icon: 'success',
            duration: 2000
          })
          
          // 清空表单
          this.clearFormData()
          
          // 刷新今日记录
          this.loadTodayRecords()
          
          // 震动反馈
          uni.vibrateShort()
          
        } else {
          throw new Error(result.result.message || '保存失败')
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('保存记录失败:', error)
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 加载今日记录
    async loadTodayRecords() {
      try {
        const today = new Date()
        const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`
        
        const result = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'list',
            data: {
              date: todayStr
            }
          }
        })
        
        if (result.result.success) {
          this.todayRecords = result.result.data || []
          // 按时间倒序排列
          this.todayRecords.sort((a, b) => b.time.localeCompare(a.time))
        }
        
      } catch (error) {
        console.error('加载今日记录失败:', error)
      }
    },
    
    // 查看所有记录
    viewAllRecords() {
      uni.switchTab({
        url: '/pages/milk-record/milk-record'
      })
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, #fff5f8 0%, #ffffff 100%);
  padding: 0;
}

.header {
  background: linear-gradient(135deg, #ff6b9d, #ff8a9b);
  padding: 60rpx 40rpx 40rpx;
  color: white;
}

.header-content {
  text-align: center;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
}

.subtitle {
  font-size: 26rpx;
  opacity: 0.9;
  display: block;
}

.voice-main-section {
  padding: 40rpx 30rpx;
}

.example-section {
  margin-bottom: 50rpx;
}

.example-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
  display: block;
}

.example-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.example-item {
  background-color: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  padding: 20rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s ease;
}

.example-item:active {
  background-color: #e9ecef;
  transform: scale(0.98);
}

.example-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  flex: 1;
}

.example-icon {
  font-size: 32rpx;
  opacity: 0.6;
}

.voice-recorder-section {
  text-align: center;
  margin-bottom: 50rpx;
}

.voice-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
  display: block;
}

.form-preview {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.preview-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.preview-clear {
  font-size: 26rpx;
  color: #ff6b9d;
  padding: 8rpx 16rpx;
}

.preview-content {
  margin-bottom: 30rpx;
}

.preview-item {
  display: flex;
  margin-bottom: 16rpx;
  align-items: center;
}

.preview-label {
  font-size: 28rpx;
  color: #666;
  width: 140rpx;
  flex-shrink: 0;
}

.preview-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  flex: 1;
}

.action-section {
  display: flex;
  gap: 20rpx;
}

.btn-secondary,
.btn-primary {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-secondary {
  background-color: #f8f9fa;
  color: #666;
  border: 1rpx solid #e9ecef;
}

.btn-primary {
  background: linear-gradient(135deg, #ff6b9d, #ff8a9b);
  color: white;
}

.empty-state {
  text-align: center;
  padding: 80rpx 40rpx;
  background-color: white;
  border-radius: 16rpx;
  margin-bottom: 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
  opacity: 0.3;
  display: block;
}

.empty-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
  display: block;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  display: block;
}

.recent-records {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 0 30rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.recent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.recent-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.recent-count {
  font-size: 24rpx;
  color: #ff6b9d;
  background-color: #ffe6f0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.recent-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.recent-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.recent-item:last-child {
  border-bottom: none;
}

.recent-time {
  font-size: 26rpx;
  color: #666;
  font-weight: bold;
}

.recent-info {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.recent-amount {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.recent-type {
  font-size: 24rpx;
  color: #999;
}

.recent-empty {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 26rpx;
}

.view-more {
  text-align: center;
  padding: 20rpx 0;
  color: #ff6b9d;
  font-size: 26rpx;
}

.quick-tips {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 0 30rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.tips-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.tip-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  display: block;
}
</style> 